#include "QImageViewer.h"
#include <QPainter>

QImageViewer::QImageViewer(QWidget *parent)
    : QLabel(parent,0)
{
}

QImageViewer::~QImageViewer()
{
    m_init = false;
}
void QImageViewer::setImage(QString s)
{
    if(!m_init)
    {
        m_x = this->geometry().left();
        m_y = this->geometry().top();
        m_maxWidth = this->geometry().width();
        m_maxHeight = this->geometry().height();
        m_init = true;
    }
    m_Img.load(s,0);
    setSize(m_Img.width(),m_Img.height());
    QLabel::setGeometry(m_x,m_y,m_width,m_height);
    this->update();
}
void QImageViewer::setImage(QByteArray s)
{
    if(!m_init)
    {
        m_x = this->geometry().left();
        m_y = this->geometry().top();
        m_maxWidth = this->geometry().width();
        m_maxHeight = this->geometry().height();
        m_init = true;
    }

    QPixmap p;
    p.loadFromData(s);
    m_Img = p.toImage();
    setSize(m_Img.width(),m_Img.height());
    QLabel::setGeometry(m_x,m_y,m_width,m_height);
    this->update();
}
void QImageViewer::setSize(int width,int height)
{
    double ratio;
    if(width > m_maxWidth)
    {
        ratio = m_maxWidth * 1.0 / width ;
        setSize(m_maxWidth, height * ratio);
        return;
    }
    else
    {
        m_width = width;
    }
    if(height > m_maxHeight)
    {
        ratio = m_maxHeight * 1.0 / height ;
        setSize(width*ratio, m_maxHeight);
        return;
    }
    else
    {
        m_height = height;
    }
}

void QImageViewer::setGeometry(int x, int y, int width, int height)
{
    m_maxWidth = width;
    m_maxHeight = height;
    QLabel::setGeometry(QRect(x,y,width,height));
    setSize(m_Img.width(),m_Img.height());
}
void QImageViewer::setGeometry(const QRect & r)
{
    QLabel::setGeometry(r);
    setSize(m_Img.width(),m_Img.height());
}

void QImageViewer::paintEvent(QPaintEvent * event)
{
    QPainter painter (this);
    painter.drawImage(QRect(0,0,m_width,m_height),m_Img);
    return;
}
